package com.zrq.secondkill.service.impl;

import com.zrq.secondkill.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *使用redis实现的session,每个用户对应一个哈希表
 * @author zrq
 */
@Service
public class SessionServiceImpl implements SessionService {

    final
    RedisTemplate redisTemplate;

    public SessionServiceImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void setAttribute(String token, String key, Object value, @Nullable Integer expire) {
        redisTemplate.opsForHash().put(token,key,value);

        //设置session过期时间
        if(expire!=null){
            redisTemplate.expire(token,expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public Object getAttribute(String token, String key, @Nullable Integer expire) {
        Object o = redisTemplate.opsForHash().get(token, key);

        if(expire!=null){
            redisTemplate.expire(token,expire, TimeUnit.SECONDS);
        }

        return o;
    }


}
